<?php

namespace app\admin\controller\shop;

use app\admin\model\Shoporder;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 优惠券
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{

    /**
     * Coupon模型对象
     * @var \app\admin\model\shop\Coupon
     */
    protected $model = null;
    protected $searchFields = 'shop.name,name';
    protected $noNeedRight = ['sendCoupon'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shop\Coupon;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("isSysList", $this->model->getIsSysList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     * @throws DbException|Exception
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['shop'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as &$row) {
                $rule = json_decode($row['rule'], true);

                //查询包厢
                $roomModel = new \app\admin\model\Shoproom();
                $roomInfo = $roomModel->where('id', 'in', $rule['room'])->select();

                $roomArr = array();
                foreach ($roomInfo as $room) {
                    $roomArr[] = $room['name'];
                }

                $row['room'] = implode(',', $roomArr);
                $row['week'] = $rule['week'];
                $row['time'] = $rule['time'];

            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);

        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $params = $this->preExcludeFields($params);

        $room = json_decode("[" . $params['room_id'] . "]");
        $week = json_decode($params['week']);
        $time = $params['time'];

        unset($params['room_id']);
        unset($params['week']);
        unset($params['time']);

        $notice1 = ["name" => '不能与其他优惠一起使用'];
        $notice2 = ["name" => '不能与其他平台券一起使用'];

        $params['rule'] = json_encode(['room' => $room, 'week' => $week, 'time' => $time, 'notice' => [$notice1, $notice2]]);
        $params['status'] = 'doing';
        $params['create_time'] = time();

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $rule = json_decode($row['rule'], true);

            $row['room_id'] = json_encode($rule['room']);
            $row['week'] = json_encode($rule['week']);
            $row['time'] = $rule['time'];

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $room = json_decode("[" . $params['room_id'] . "]");
        $week = json_decode($params['week']);
        $time = $params['time'];

        unset($params['room_id']);
        unset($params['week']);
        unset($params['time']);

        $notice1 = ["name" => '不能与其他优惠一起使用'];
        $notice2 = ["name" => '不能与其他平台券一起使用'];

        $params['rule'] = json_encode(['room' => $room, 'week' => $week, 'time' => $time, 'notice' => [$notice1, $notice2]]);
        $params['status'] = 'doing';

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function sendCoupon($ids = null)
    {
        if (empty($ids)) $this->error('券Id不能为空');

        $couponInfo = $this->model->where('id', $ids)->find();
        if (empty($couponInfo)) $this->error('没有找到券码信息');

        //查询所有在店铺消费过的用户ID，仅限棋牌
        $shopOrderModel = new Shoporder();
        $users = $shopOrderModel->where('shop_id', $couponInfo['shop_id'])->where('status', 'in', ['done', 'doing'])->select();
        if (empty($users)) $this->error('该店铺暂未有消费者');

        $newUsers = [];
        foreach ($users as $user) {
            $newUsers[] = $user['user_id'];
        }
        //数组去重
        $newUserArr = array_unique($newUsers);

        $insertArr = array();
        foreach ($newUserArr as $user) {
            $inserVal = array();
            $inserVal['user_id'] = $user;
            $inserVal['coupon_id'] = $ids;
            $inserVal['create_time'] = time();
            $inserVal['status'] = 'unuse';
            $inserVal['valid_time'] = time() + $couponInfo['valid_day'] * 24 * 60 * 60;

            $insertArr[] = $inserVal;
        }
        //发券
        Db::name('user_coupon')->insertAll($insertArr);

        $this->success('发放完毕');
    }

}
